﻿(function () {
    var $shopList = $('#shopList'),
        $mapTipMsg = $('#mapTipMsg'),
	    $txtAddress = $('#txtAddress'),
        $mapType = $('#mapType');

    var MapZoom = 20;/*店铺定位后地图缩放大小*/
    var TAG_ShowAllSignedShop = 'showAllSignedShop';

    /*当前店铺坐标*/
    var curLocation,
        curShop,
        signedShopData,
        signingShopData,
        options,
        cacheMapData,
        map,
        marker,
        isSignMaping = false;

    var api = {},
        defauls = {
            "MapCity": "深圳",
            "MapZoom": 15,
            "FromType": 0,
            "ReturnUrl": null,
            "MapData": [
                {
                    "Id": "1",
                    "MapLabel": null,
                    "InfoWindowMsg": "罗湖区翠竹路富安娜前人行道",
                    "MapLocation":
                        {
                            "lng": 114.1373,
                            "lat": 22.56313
                        },
                    "Address": "罗湖区翠竹路富安娜前人行道",
                    "City": "深圳"
                }],
            "ChangeLocationBtnText": "修改地图位置"
        };
    ;

    function fnTipMsg(msg) {
        alert(msg);
    }

    function Debug(obj) {
        console.log(obj)
    }

    String.prototype.formatWith = function () {
        var args = arguments, self = this;;
        for (var i = 0, len = args.length; i < len; i++) {
            self = self.replace(new RegExp('\\{' + i + '\\}', 'g'), args[i]);
        }
        return self;
    };

    api.saveCurLoc = function () {
        if (!curShop || !curLocation) {
            return fnTipMsg('参数错误！');
        }
        var saveData = { Id: curShop.Id, lat: curLocation.lat, lng: curLocation.lng, t: Math.random() };
        var data = mapCommon.callback(options, saveData);
        if ($.isPlainObject(data)) {
            if (data.errorCode === 0) {
                fnTipMsg(data.msg || '保存成功');
                updateCacheMapData(saveData.Id, saveData.lat, saveData.lng);
                if ($mapType.val() == "1") {
                    $mapType.triggerHandler('change');
                } else {
                    $shopList.find('option:selected').remove();
                    if ($shopList.find('option').length == 0) {
                        alert('没有未标注的点了');
                        $mapType.val(1).triggerHandler('change');
                        fnSetSignStatus(false);
                    } else {
                        $shopList.triggerHandler('change');
                    }
                }
            } else {
                fnTipMsg(data.msg || '保存失败');
            }
        }
    };

    /*更新缓存中信息*/
    function updateCacheMapData(id, lat, lng) {
        $.each(cacheMapData, function (i, item) {
            if (item.Id === id) {
                item.MapLocation = { lat: lat, lng: lng };
                return false;
            }
        });
    }

    function fnShowMapShopInfo(shop, isNotCenterAndZoom) {
        var content = shop.InfoWindowMsg;
        content += '<p><center><a href="javascript:;" onclick="signShopApi.changeShopMapLoc(\'{0}\')">修改店铺地图位置</a></center></p>'.formatWith(shop.Id);
        var point = new BMap.Point(shop.MapLocation.lng, shop.MapLocation.lat);
        !isNotCenterAndZoom && map.centerAndZoom(point, MapZoom);
        var infoWindow = new BMap.InfoWindow(content, { offset: new BMap.Size(0, -20) });
        map.openInfoWindow(infoWindow, point);
    }

    api.changeShopMapLoc = function (shopId) {
        $shopList.val(shopId).triggerHandler('change');
        fnSetSignStatus(true);
        map.setZoom(15);
        map.clearOverlays();
    };

    /*切换地图是否正在标记状态*/
    function fnSetSignStatus(isSigning) {
        $mapTipMsg.text('点击地图即可标注位置').toggle(isSigning);
        isSignMaping = isSigning;
    }

    /*显示所有已标记的点*/
    function fnShowAllSignedShop(b) {
        map.clearOverlays();
        map.reset();
        //       map.centerAndZoom('深圳', 12);
        $.each(signedShopData, function (i, item) {
            var label = new BMap.Label(item.MapLabel, { offset: new BMap.Size(19, 5) });
            var marker = new BMap.Marker(new BMap.Point(item.MapLocation.lng, item.MapLocation.lat), {});
            marker.addEventListener("click", function (e) {
                Debug(item);
                curShop = item;
                $shopList.val(item.Id);
                fnShowMapShopInfo(item);
            });
            marker.addEventListener("mouseover", function (e) {
                Debug(item)
                curShop = item;
                fnShowMapShopInfo(item, true);
            });
            map.addOverlay(marker);
            marker.setLabel(label);
        });
    }

    function fnAppendShopList(data) {
        $.each(data || [], function (i, item) {
            $('<option/>', { value: item.Id, text: item.Address })
                .data(item).appendTo($shopList);
        });
        $shopList.triggerHandler('change');
    }

    api.init = function (opts) {
        options = $.extend(true, {}, defauls, opts);
        cacheMapData = options.MapData || [];
        map = new BMap.Map("allmap");
        map.enableScrollWheelZoom();
        map.centerAndZoom(options.MapCity, options.MapZoom);
        map.addEventListener("click", function (r) {
            Debug(arguments)
            if (isSignMaping) {
                map.clearOverlays();
                signLocation(r.point);
            }
        });
        var showAllSignedShop = $('<option/>', { text: '在地图上显示所有已标注', value: TAG_ShowAllSignedShop });
        $mapType = $('#mapType').change(function () {
            var v = this.value;
            $shopList.empty();
            map.clearOverlays();
            switch (v) {
                case '1':
                    $shopList.append(showAllSignedShop);
                case '2':
                    fnGetShopData(this.value, fnAppendShopList);
                    break;
            }
        });
        $shopList.change(function () {
            if (this.value === '') {
                return;
            }
            if (this.value == TAG_ShowAllSignedShop) {
                $txtAddress.val('');
                fnSetSignStatus(false);
                return fnShowAllSignedShop();
            }
            if (isSignMaping && $mapType.val() == "1") {
                fnShowAllSignedShop(true);
            }
            fnSetSignStatus(false);
            var option = $shopList.find('option:selected'), data = option.data();
            curShop = data;
            $txtAddress.val(data.Address).attr('data-city', data.City);
            if (data.MapLocation) {
                fnShowMapShopInfo(data);
            } else {
                fnSetSignStatus(true);
                GetAddressLocation(data.Address, data.City);
            }
        });
        $('#btnSearch').click(searchMapAddress);
        $txtAddress.keyup(function (e) {
            if (e.keyCode == 13) {
                searchMapAddress();
            }
        });
        $mapType.triggerHandler('change');
    };

    function searchMapAddress() {
        var v = $.trim($txtAddress.val());
        var city = $txtAddress.attr('data-city');
        v.length && myGeo.getPoint(v, function (point) {
            if (point) {
                if (isSignMaping) {
                    map.clearOverlays();
                    signLocation(point);
                } else {
                    map.centerAndZoom(point, 15);
                }
            } else {
                map.centerAndZoom(city, 12);
                alert("没有搜索到位置，请修改地址重新搜索!");
            }
        }, city);
    }


    function ParseLocation(float) {
        if (float == null) {
            return 0;
        }
        return parseFloat(float, 10);
    }

    function fnGetShopData(type, callback) {
        var data;
        if (type == 1) {
            data = signedShopData = $.grep(cacheMapData, function (item) {
                return !!item.MapLocation;
            });
        } else {
            data = signingShopData = $.grep(cacheMapData, function (item) {
                return !item.MapLocation;
            });
        }
        callback(data);
    }

    function signLocation(point) {
        point = new BMap.Point(point.lng, point.lat);
        curLocation = point;
        map.centerAndZoom(point, MapZoom);
        marker = new BMap.Marker(point); // 创建点
        map.addOverlay(marker);
        var shop = curShop;
        var content = shop.InfoWindowMsg;
        content += '<p><center><a href="javascript:;" onclick="signShopApi.saveCurLoc()">保存当前地图位置</a></center></p>';
        var infoWindow = new BMap.InfoWindow(content, { offset: new BMap.Size(0, -20) });  // 创建信息窗口对象
        map.openInfoWindow(infoWindow, point);
    }

    var autoInfoWindow = new BMap.InfoWindow('系统根据地址解析到的位置，请确认位置是否准确（点击地图重新标注位置）！<br><center><a href="javascript:;" onclick="signShopApi.saveCurLoc()">保存当前地图位置</a></center>', { offset: new BMap.Size(0, -20) });  // 创建信息窗口对象

    // 创建地址解析器实例
    var myGeo = new BMap.Geocoder();
    function GetAddressLocation(address, city) {
        Debug(arguments)
        map.clearOverlays();
        // marker && map.removeOverlay(marker);
        // 将地址解析结果显示在地图上,并调整地图视野
        myGeo.getPoint(address, function (point) {
            if (point) {
                curLocation = point;
                map.centerAndZoom(point, MapZoom);
                marker = new BMap.Marker(point); // 创建点
                map.addOverlay(marker);
                map.openInfoWindow(autoInfoWindow, point);
            } else {
                curLocation = null;
                map.centerAndZoom(city, 12);
                alert("系统根据地址没有解析到位置，请手动选择位置!");
            }
        }, city);
    }
    window.signShopApi = api;
})();